import { get, post, upload } from './index';

export const getDicts = key => {
    const token = uni.getStorageSync('TEMP_TOKEN');
    return get('/system/dict/data/type/' + key, null, token);
};

export const getCozeToken = async (person = false) => {
    // 获取扣子授权
    const res = await post(`/platform/cozeToken?mode=coze&platform=${!person}`);
    if (typeof res.data !== 'string' && !res.data.success) {
        setTimeout(() => {
            uni.navigateBack();
        }, 3000);
        return uni.showToast({
            title: res.data.message,
            icon: 'none',
        });
    }
    const token = res.data.data || res.data;
    return await new Promise((resolve, reject) => {
        uni.request({
            url: 'https://api.coze.cn/api/permission/oauth2/token',
            method: 'POST',
            header: {
                'Content-Type': 'application/json',
                Authorization: `Bearer ${token}`,
            },
            data: {
                grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
                duration_seconds: 86399,
            },
            success: r => {
                const data = r.data;
                if (data.access_token) {
                    const t = {
                        token: data.access_token,
                        time: new Date().getTime(),
                    };
                    if (person) {
                        uni.setStorageSync('PERSON_COZE_TOKEN', t);
                    } else {
                        uni.setStorageSync('COZE_TOKEN', t);
                    }
                    resolve(t);
                    return;
                }
                uni.showToast({
                    title: '扣子授权出错，请检查您的sdk是否设置正确',
                    icon: 'none',
                });
                setTimeout(() => {
                    uni.navigateBack();
                }, 3000);
            },
            fail: err => {
                console.log(err);
                reject(err);
            },
        });
    });
};

export const getCozeAgentDetail = (botId, token) => {
    return new Promise((resolve, reject) => {
        uni.request({
            url: 'https://api.coze.cn/v1/bot/get_online_info?bot_id=' + botId,
            method: 'GET',
            header: {
                Authorization: `Bearer ${token}`,
                'Content-Type': 'application/json',
            },
            success: r => {
                const data = r.data;
                if (data.code === 4101) {
                    uni.showToast({
                        title: '资源加载出错，请检查您的扣子智能体，页面将在5s后关闭',
                        icon: 'none',
                        duration: 5000,
                    });
                    setTimeout(() => {
                        uni.navigateBack();
                    }, 5000);
                    return;
                }
                resolve(data.data);
            },
            fail: err => {
                reject(err);
            },
        });
    });
};

export const getCozeFile = (file, token) => {
    uni.showLoading({
        title: '上传中...',
        mask: true,
    });
    return new Promise((resolve, reject) => {
        uni.uploadFile({
            url: 'https://api.coze.cn/v1/files/upload',
            method: 'POST',
            header: {
                Authorization: `Bearer ${token}`,
            },
            // #ifdef MP-WEIXIN || APP-PLUS
            filePath: file.tempFilePaths[0],
            // #endif
            // #ifdef H5
            file: file.tempFiles[0],
            // #endif
            name: 'file',
            success: async res => {
                const data = JSON.parse(res.data);
                if (data.code === 0) {
                    const fileRes = {
                        id: data.data.id,
                    };
                    const u = await upload(file);
                    fileRes.url = u.url;
                    resolve(fileRes);
                } else {
                    uni.showToast({
                        title: '上传失败,暂不支持改文件格式',
                        icon: 'none',
                    });
                    resolve(false);
                }
                uni.hideLoading();
            },
            fail: err => {
                uni.showToast({
                    title: '上传失败',
                    icon: 'none',
                });
                resolve(false);
                uni.hideLoading();
            },
        });
    });
};


export function chooseSystemFile() {
    return new Promise((resolve, reject) => {
        // #ifdef APP-PLUS
        plus.io.chooseFile({
            title: '选择文件',
            filter: '*', // 所有文件类型（或指定如 '.pdf,.docx'）
            multiple: false // 是否多选
        }, (res) => {
            const file = res.files[0];
            resolve({
                name: file.split('.').pop(),
                tempFilePaths: [plus.io.convertLocalFileSystemURL(file)], // 转换路径
            });
        }, (err) => {
            reject(err);
        });
        // #endif
    });
}

